package com.example.demo.interceptor;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author x c
 * @Email 378661553@qq.com
 * @Date Created in 2019/12/20 14:33
 */
public class AccessControlAllowOriginInterceptor implements HandlerInterceptor {
    /**
     * 执行 controller 前执行
     * 如果返回了 false 就不往下面的方法执行了
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 不指定编码格式，防止静态资源编码显示不准（比如在浏览器下载一个txt会自动在浏览器显示，如果该txt的文件编码不是UTF-8就会导致乱码）
//        response.setCharacterEncoding("UTF-8");
        //是否允许客户端携带自定义请求头
//        response.setHeader("Access-Control-Allow-Credentials", "true");
        //域名 生产环境不允许设置为“*”
//        response.setHeader("Access-Control-Allow-Origin", "*");
//        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
//        response.setHeader("Access-Control-Max-Age", "3600");
//        response.setHeader("Access-Control-Allow-Headers", "DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization,SessionToken");
        // 返回true才会执行后面的代码 ==> postHandle
        return true;
    }

    /**
     * 执行controller方法后执行
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    /**
     * 执行完 postHandle 后执行
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
